<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="form-box">
            <div class="form-title">新增学生</div>
            <el-form :model="formList" ref="formList" slot="form" label-width="80px">
                <div class="form-item-title">
                    <span class="note-css"></span>
                    <span class="title-level">基本信息</span>
                </div>
                <el-row class="row-bg" :gutter="41">
                    <el-col :span="12">
                        <el-form-item label="学生姓名" prop="studentName" :rules="name">
                          <el-popover placement="top-start" trigger="focus" content="长度在12个字符以内">
                            <el-input slot="reference" :maxlength="12" placeholder="请输入学生姓名" v-model="formList.studentName" style="width:95%;"></el-input>
                          </el-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="sex" >
                            <el-radio-group v-model="formList.sex">
                                <el-radio label="0">男</el-radio>
                                <el-radio label="1">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row class="row-bg" :gutter="41">
                    <el-col :span="12">
                        <el-form-item label="学籍号" prop="schoolRoll" :rules="schoolRoll">
                          <el-popover placement="top-start" trigger="focus" content="长度在20个字符以内。">
                            <el-input placeholder="请输入学籍号" slot="reference" :maxlength="20" v-model="formList.schoolRoll" style="width:95%;"></el-input>
                          </el-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="出生日期" prop="birthday">
                            <el-date-picker v-model="formList.birthday" type="date" :editable="false" placeholder="选择日期" :picker-options="pickerOptions0" style="width:95%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="form-item-title">
                    <span class="note-css"></span>
                    <span class="title-level">家长信息</span>
                </div>
                <el-row class="row-bg" :gutter="41" v-for="(item, index) in formList.contactWayList" :key="index">
                  <el-col :span="12">
                      <el-form-item :label="'联系人 ' + (index + 1)" :prop="'contactWayList.' + index + '.phone'" :rules="index==0?namephone:otherContactWay">
                        <el-popover placement="top-start" trigger="focus" content="请输入11位手机号">
                          <el-input style="width:95%" slot="reference" :maxlength="11"  placeholder="请输入手机号" v-model="item.phone" ></el-input>
                        </el-popover>
                      </el-form-item>
                  </el-col>
                  <el-col :span="1" v-if="index != 0">
                        <el-button type="text" class="delBtn" @click="removeContactWay(index)"><i class="el-icon-delete"></i></el-button>
                  </el-col>
                </el-row>
                <el-button v-if="formList.contactWayList.length < 5" type="text" @click="addContactWay" class="addBtn btn-success"><i class="el-icon-plus"></i> 继续添加</el-button>
                <!-- <el-row class="row-bg" :gutter="41">
                    <el-col :span="12">
                        <el-form-item label="联系方式" prop="phone" :rules="namephone">
                          <el-popover placement="top-start" trigger="focus" content="请输入11位手机号">
                            <el-input slot="reference" :maxlength="11" placeholder="请输入手机号" v-model="formList.phone" style="width:95%;"></el-input>
                          </el-popover>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label=""></el-form-item>
                    </el-col>
                </el-row> -->
                <p class="title-p"></p>
                <div class="box">
                    <el-button @click="cancel">取消</el-button>
                    <el-button @click="submitForm('formList')" type="primary">立即创建</el-button>                   
                </div>
                <p class="title-p"></p>
            </el-form>
        </div>    
    </div>
</template>
<script>
import moment from "moment";
import Levelbar from "../layout/Levelbar";
import { addStudentIntoClass } from "api/classAll";
import validate from "@/utils/validate";
export default {
  name: "addNewStudent",
  components: { Levelbar },
  data() {
    return {
      formList: {
        studentName: "",
        sex: "0",
        schoolRoll: "",
        birthday: "",
        phone: "",
        contactWayList: [{
            phone: ''
        }]
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7;
        }
      },
      name: [
        { required: true, message: "请输入内容", trigger: "blur" },
        { min: 0, max: 12, message: "请输入合法的内容", trigger: "blur" }
      ],
      nameRoll: [
        { message: "请输入内容", required: true },
        { message: "请输入合法学籍", trigger: "blur", pattern: /^\d{0,20}$/ }
      ],
      namephone: [
        ...validate.phoneRequired(),
      ],
      otherContactWay: [
        ...validate.phone(),
      ],
      nameBirthday: [
        { type: "date", required: true, message: "请选择日期", trigger: "change" }
        // { message: "请输入内容", required: true },
        // {
        //   message: "请输入合法的生日",
        //   trigger: "blur",
        //   pattern: /^(19|20)\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])$/
        // }
      ],
      resource: { required: true, message: "请选择性别", trigger: "change" },
      schoolRoll: [
        { pattern: /^[A-Za-z0-9]+$/, message: "只允许输入数字和字母" },
        { min: 1, max: 20, message: "长度在20个字符以内", trigger: "blur" }
      ]
    };
  },
  methods: {
    addContactWay() {
        this.formList.contactWayList.push({
          phone: ''
        });
    },
    removeContactWay(index) {
        if (index !== -1) {
          this.formList.contactWayList.splice(index, 1);
        }
    },
    formatDate(str) {
      if (str) {
        let Year = null,
          Month = null,
          date = null;
        Year = ~~str.getFullYear();
        Month = ~~str.getMonth() + 1;
        date = ~~str.getDate();
        return `${Year}-${Month + "".length > 0
          ? Month
          : "0" + Month}-${date.length > 1 ? date : "0" + date}`;
      }
    },
    submitForm(formList) {
      let phoneArray = [];
      this.formList.contactWayList.forEach(item => {
          if(item.phone) {
              phoneArray.push(item.phone);
          }
      });
      const items = new Set(phoneArray);
      if(items.size != phoneArray.length) {
          this.$message.error('联系人号码重复');
          return;
      }
      this.$refs[formList].validate(valid => {
        if (valid) {
          let phones = [];
          this.formList.phone = this.formList.contactWayList[0].phone;
          if(this.formList.contactWayList.length >1) {
              this.formList.contactWayList.forEach(function(item, index) {
                  if(index != 0 && item.phone) {
                      phones.push(item.phone);
                  }
              });
          }
          let birthDay =
            this.formList.birthday == ""
              ? ""
              : moment(this.formList.birthday).format("YYYY-MM-DD"); // 生日

          this.$confirm("确认新增学生？", " ", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: " "
          })
            .then(() => {
              addStudentIntoClass(
                this.formList.studentName,
                this.formList.sex,
                this.formList.schoolRoll,
                birthDay,
                this.formList.phone,
                this.$route.params.classId,
                this.$route.params.schoolId,
                phones
              ).then(data => {
                this.$store.dispatch("UpdateCache");
                this.$router.push({
                  path: `/classStudent/studentList/${this.$route.params.id}`
                });
                this.$message({
                  message: "新增成功！",
                  type: "success"
                });
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消"
              });
            });
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.$router.go(-1);
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  $bgcolor: #fff;

  @mixin showTitle() {
    background: $bgcolor;
    box-shadow: 0px 1px 2px #999;
    -webkit-box-shadow: 0px 1px 2px #999;
  }
    .delBtn {
        font-size: 20px;
        color:#999;
    }
    .addBtn{
        margin-left:94px;
        font-size:14px;
        color:#ff5e2c;
    }
  .form-box {
    padding: 0px 50px 0;
    @include showTitle();
    .form-title {
      text-align: center;
      font-size: 18px;
      color: #333;
      height: 78px;
      line-height: 78px;
      font-weight: bold;
      border-bottom: 1px solid #ddd;
    }
    .form-item-title {
      margin-top: 30px;
      margin-bottom: 15px;
      font-size: 14px;
      color: #333;
      .note-css {
        vertical-align: middle;
        display: inline-block;
        width: 4px;
        height: 14px;
        margin-right: 16px;
        border-left: 3px solid #ff5e2c;
      }
    }
    .row-bg {
      padding-left: 16px;
    }
  }

  .title-p {
    color: #333;
    font-size: 18px;
    padding: 20px 0;
  }

  .box {
    text-align: center;
  }
}
</style>
